A format string is a string that contains placeholders, usually represented by special characters such as "%s" or "{}", depending on the technology
in use. These placeholders are replaced by values when the string is printed or logged. Thus, it is required that a string is valid and arguments
match replacement fields in this string.
This applies to the % operator, the str.format method, and loggers from the logging module. Internally, the latter use the %-formatting
. The only
difference is that they will log an error instead of raising an exception when the provided arguments are invalid.
Formatted string literals (also called "f-strings"; available since Python 3.6) are generally simpler to use, and any syntax mistake will cause a
failure at compile time. However, it is easy to forget curly braces, which will not lead to any detectable errors.
This rule raises an issue when:
- A string formatted with
%
will not return the expected text because some arguments are unused.
- A string formatted with
str.format
will not return the expected string because some arguments are unused.
- An "f-string" doesn’t contain any replacement field, which probably means some curly braces are missing.
- Loggers will log an error because their message is not formatted properly.
Rule S2275 covers cases where formatting a string will raise an exception.